package com.example.community.controller;

import com.example.community.annotation.LoginRequired;
import com.example.community.entity.User;
import com.example.community.service.FollowService;
import com.example.community.service.LikeService;
import com.example.community.service.UserService;
import com.example.community.util.CommunityConstant;
import com.example.community.util.CommunityUtil;
import com.example.community.util.HostHolder;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

/**
 * @Author: huang
 * @Date: 2021/9/19 10:16
 * @Description:    访问设置页面
 */
@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${qiniu.key.access}")
    private String accessKey;

    @Value("${qiniu.key.secret}")
    private String secretKey;

    @Value("${qiniu.bucket.header.name}")
    private String headerBucketName;

    @Value("${quniu.bucket.header.url}")
    private String headerBucketUrl;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;

    /**
     *
     * @param model
     * @return 实现用户上传表单时，直接将表单数据提交给云服务器
     *              1）生成上传凭证：用于七牛云对服务器的识别，包括上传文件的名称，以及上传后期待的七牛云响应
     *           2）上传凭证和上传文件名 传给模板。模板利用所需的数据重新构成表单，并将表单以异步的方式提交给七牛云处理
     */
    @LoginRequired
    @RequestMapping(path = "/setting", method = RequestMethod.GET)
    public String getSettingPage(Model model) {
        // 上传文件名称
        String fileName = CommunityUtil.generateUUID();
        // 设置响应信息
        StringMap policy = new StringMap();
        // 指定成功时返回json字符串，“code:0”
        policy.put("returnBody", CommunityUtil.getJSONString(0));
        // 生成上传凭证
        Auth auth = Auth.create(accessKey, secretKey);
        // 参数1 存储空间的名字；参数2 上传文件名；参数3 key过期时间；参数4 响应信息
        String uploadToken = auth.uploadToken(headerBucketName, fileName, 3600, policy);

        model.addAttribute("uploadToken", uploadToken);
        model.addAttribute("fileName", fileName);

        return "/site/setting";
    }

    /**
     * 更新头像路径
     */
    @RequestMapping(path = "/header/url", method = RequestMethod.POST)
    @ResponseBody
    public String updateHeaderUrl(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return CommunityUtil.getJSONString(1, "文件名不能为空!");
        }

        //访问七牛云中的数据url
        String url = headerBucketUrl + "/" + fileName;
        userService.updateHeader(hostHolder.getUser().getId(), url);

        return CommunityUtil.getJSONString(0);
    }


    /**
     *
     * @param headerImage    浏览器传过来的头像文件
     * @param model         用于返回模板信息
     * @return
     */
    //废弃
    @LoginRequired
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String uploadHeader(MultipartFile headerImage, Model model) {
        //1.空值处理
        if (headerImage == null) {
            model.addAttribute("error", "您还没有选择图片!");
            return "/site/setting";
        }

        //2.每个用户上传到服务器的图片名可能相同，我们先用substring分割出文件后缀，后续生成随机字符拼接存到服务器中
        //获得图片原始名
        String fileName = headerImage.getOriginalFilename();
        //分割文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //进行判断用户上传文件格式
        System.out.println(suffix);
        if (StringUtils.isBlank(suffix) ||(!suffix.equals(".png") && !suffix.equals( ".jpg") && !suffix.equals(".jpeg"))) {
            model.addAttribute("error", "文件格式不正确！");
            return "/site/setting";
        }
        //3.生成随机字符串拼接后缀suffix
        fileName = CommunityUtil.generateUUID() + suffix;
        //4.确定文件路径。为什么还要加文件名？这是因为后面存储文件transferTo方法，它会将最后的路径当成文件进行存储
        File dest = new File(uploadPath + "/" + fileName);
        //5.存储文件
        try {
            headerImage.transferTo(dest);
        } catch (IOException e) {
            logger.error("上传文件失败：" + e.getMessage());
            throw new RuntimeException("上传文件失败，服务器发生异常！",e);
        }

        //5.更新当前用户头像路径（web 访问路径）
        //http://localhost:8080/community/user/header/xxx.png，这也是获取当前头像的路径，后面我们会写访问头像的方法
        User user = hostHolder.getUser();
        String headerUrl = domain + contextPath + "/user/header/" + fileName;
        userService.updateHeader(user.getId(), headerUrl);
        return "redirect:/index";
    }

    /**
     *获取头像
     * @param fileName
     * @param response
     *                  我们返回的是一个二进制文件，我们用void。
     */
    //废弃
    @RequestMapping(path = "/header/{fileName}", method = RequestMethod.GET)
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        //1.获取服务器存放的图片路径
        fileName = uploadPath + "/" + fileName;
        //2.我们response返回的是一个二进制字节流文件，每个图片的后缀不一样。获取后缀png
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        //3.响应图片，设置返回类型。image/png 其实 image/.png浏览器会自动帮我们把.去掉
        response.setContentType("image/" + suffix);
        //这里try（）{}的写法是java7的语法，括号里的内容会自动在finally里关闭。
        try (
                //创建文件输入流，边读边输入
                FileInputStream fileInputStream = new FileInputStream(fileName);
                //我们字节流响应
                OutputStream os = response.getOutputStream();
                //建立缓冲区，提高输入输出效率
                ){
            byte[] buffer = new byte[1024];
            int b = 0;
            //每次从文件输入流中读取1字节
            while((b = fileInputStream.read(buffer)) != -1) {
                //输出
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            logger.error("读取头像失败"+e.getMessage());
        }
    }

    @RequestMapping(path = "/updatePassword", method = RequestMethod.POST)
    public String updatePassword(String originalPassword, String newPassword, String confirmPassword, Model model) {
        User user = hostHolder.getUser();
        System.out.println(originalPassword);
        Map<String, Object> map = userService.updatePassword(user, originalPassword, newPassword, confirmPassword);
        if (map.containsKey("rightMsg")) {
            //修改成功
            model.addAttribute("rightMsg", map.get("rightMsg"));
            return "redirect:/logout";
        }else {
            model.addAttribute("originalPasswordMsg", map.get("originalPasswordMsg"));
            model.addAttribute("newPasswordMsg", map.get("newPasswordMsg"));
            model.addAttribute("confirmPasswordMsg", map.get("confirmPasswordMsg"));
            model.addAttribute("errorMsg", map.get("errorMsg"));
            return "/site/setting";
        }
    }

    //个人主页
    @RequestMapping(path = "/profile/{userId}", method = RequestMethod.GET)
    public String getProfilePage(@PathVariable("userId") int userId, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw  new RuntimeException("该用户不存在!");
        }

        //把用户放到model中
        model.addAttribute("user", user);
        //点赞数量
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount", likeCount);

        //这个用户关注数量
        long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followeeCount",followeeCount);
        //这个用户粉丝数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("followerCount", followerCount);
        //查询当前用户对这个用户是否已关注
        boolean hasFollowed = false;
        if (hostHolder.getUser() != null) {
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(), ENTITY_TYPE_USER, userId);
        }
        model.addAttribute("hasFollowed", hasFollowed);
        return "/site/profile";
    }

}
